// 材质管理器 - 专门处理材质相关逻辑
import * as THREE from 'three'
import { CONFIG, ERROR_MESSAGES } from '../config/constants.js'

export class MaterialManager {
  constructor() {
    this.loadedTextures = new Map()
    this.textureLoader = new THREE.TextureLoader()
  }

  async loadTexture(path) {
    if (this.loadedTextures.has(path)) {
      return this.loadedTextures.get(path)
    }

    return new Promise((resolve, reject) => {
      this.textureLoader.load(
        path,
        (texture) => {
          texture.wrapS = THREE.RepeatWrapping
          texture.wrapT = THREE.RepeatWrapping
          this.loadedTextures.set(path, texture)
          resolve(texture)
        },
        undefined,
        (error) => {
          console.error(ERROR_MESSAGES.TEXTURE_LOAD_FAILED, error)
          reject(error)
        }
      )
    })
  }

  createMaterial(type, options = {}) {
    const materialOptions = {
      ...CONFIG.DEFAULT_MATERIAL,
      ...options
    }

    switch (type) {
      case 'MeshBasicMaterial':
        return new THREE.MeshBasicMaterial(materialOptions)
      case 'MeshLambertMaterial':
        return new THREE.MeshLambertMaterial(materialOptions)
      case 'MeshPhongMaterial':
        return new THREE.MeshPhongMaterial({
          ...materialOptions,
          shininess: 100
        })
      case 'MeshStandardMaterial':
        return new THREE.MeshStandardMaterial(materialOptions)
      case 'MeshPhysicalMaterial':
        return new THREE.MeshPhysicalMaterial({
          ...materialOptions,
          clearcoat: 0.3,
          clearcoatRoughness: 0.25
        })
      default:
        return new THREE.MeshStandardMaterial(materialOptions)
    }
  }

  updateTextureProperties(texture, params) {
    if (!texture) return
    
    texture.repeat.set(params.repeatU || 1, params.repeatV || 1)
    texture.offset.set(params.offsetU || 0, params.offsetV || 0)
    texture.needsUpdate = true
  }

  dispose() {
    this.loadedTextures.forEach(texture => texture.dispose())
    this.loadedTextures.clear()
  }
}